package com.poisonh.unifiedauth.dialog;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lzy.okhttputils.model.HttpParams;
import com.poisonh.unifiedauth.R;
import com.poisonh.unifiedauth.utils.ConstantUitls;
import com.poisonh.unifiedauth.utils.MyHttpsUtils;
import com.poisonh.unifiedauth.utils.RandomUtils;
import com.poisonh.unifiedauth.utils.ToastUtils;

/**
 * 添加密码箱dialog
 * Created by PoisonH on 2016/7/11.
 */
public class AddPasswordBoxDialogFragment extends BaseDialogFragment implements View.OnClickListener
{
    protected LinearLayout mLeftBtn;
    protected LinearLayout mRightBtn;
    protected TextView mTvTitle;
    protected TextView mTvRight;

    private EditText mltAddpasswordBoxName;
    private EditText mltAddpasswordBoxAccount;
    private EditText mltAddpasswordBoxPassword;
    private EditText mltAddpasswordBoxWebsite;

    private TextView mTvRandom;

    private String mStrId;
    private String mStrName;
    private String mStrAccount;
    private String mStrPasswd;
    private String mStrWebSite;
    private boolean isUpdate = false;

    @Override
    public void onStart()
    {
        super.onStart();

        // 设置宽度为屏宽、靠近屏幕顶部。
        Window window = getDialog().getWindow();
        window.setBackgroundDrawable(new ColorDrawable(0xff000000));
        WindowManager.LayoutParams wlp = window.getAttributes();
        wlp.gravity = Gravity.TOP;
        wlp.width = WindowManager.LayoutParams.MATCH_PARENT;
        wlp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(wlp);

        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        window.setLayout(dm.widthPixels, getDialog().getWindow().getAttributes().height);

    }

//    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
//    {
//        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
//        mStrUserId = PreferencesUtils.getString(getActivity(), "ID");
//        View view = inflater.inflate(R.layout.layout_dialog_addpassword, null);
//        return view;
//    }

    @Override
    protected View loadView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        return inflater.inflate(R.layout.layout_dialog_addpassword, null);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState)
    {
        super.onViewCreated(view, savedInstanceState);
        mLeftBtn = (LinearLayout) view.findViewById(R.id.ib_left_btn);
        mRightBtn = (LinearLayout) view.findViewById(R.id.ib_right_btn);
        mTvTitle = (TextView) view.findViewById(R.id.tv_common_title);
        mTvRight = (TextView) view.findViewById(R.id.tv_right_txt);

        mltAddpasswordBoxName = (EditText) view.findViewById(R.id.mlt_addpasswordbox_name);
        mltAddpasswordBoxAccount = (EditText) view.findViewById(R.id.mlt_addpasswordbox_account);
        mltAddpasswordBoxPassword = (EditText) view.findViewById(R.id.mlt_addpasswordbox_password);
        mltAddpasswordBoxWebsite = (EditText) view.findViewById(R.id.mlt_addpasswordbox_website);

        mTvRandom = (TextView) view.findViewById(R.id.tv_random);
        mTvRandom.setOnClickListener(this);
        initTitle();

        if (ConstantUitls.HAVE)
        {
            mStrId = getArguments().getString("ID");
            mStrAccount = getArguments().getString("ACCOUNT");
            mStrPasswd = getArguments().getString("PASSWORD");
            mStrWebSite = getArguments().getString("URL");
            mStrName = getArguments().getString("NAME");

            isUpdate = true;

            mltAddpasswordBoxName.setText(mStrName + "");
            mltAddpasswordBoxAccount.setText(mStrAccount + "");
            mltAddpasswordBoxPassword.setText(mStrPasswd + "");
            if (mStrWebSite == null || mStrWebSite.isEmpty() || mStrWebSite.length() <= 0)
            {
                mltAddpasswordBoxWebsite.setText("");
            } else
            {
                mltAddpasswordBoxWebsite.setText(mStrWebSite + "");
            }
            ConstantUitls.HAVE = false;
        }
    }

    /**
     * 初始化标题栏
     */
    private void initTitle()
    {
        mLeftBtn.setOnClickListener(this);
        mTvTitle.setText(R.string.addpasswordbox_title);
        mRightBtn.setVisibility(View.GONE);
        mTvRight.setText(R.string.addpasswordbox_complete);
        mTvRight.setVisibility(View.VISIBLE);
        mTvRight.setOnClickListener(this);
    }

    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.ib_left_btn:
                dismiss();
                break;
            case R.id.tv_right_txt:
                mStrName = mltAddpasswordBoxName.getText().toString().replaceAll("\\s*", "");
                mStrAccount = mltAddpasswordBoxAccount.getText().toString().replaceAll("\\s*", "");
                mStrPasswd = mltAddpasswordBoxPassword.getText().toString().replaceAll("\\s*", "");
                mStrWebSite = mltAddpasswordBoxWebsite.getText().toString().replaceAll("\\s*", "");
                if (checkEmpty())
                {
                    mTvRight.setEnabled(false);
                    if (isUpdate)
                    {
                        updatePassWdBox();
                    } else
                    {
                        addPassBox();
                    }
                }
                break;
            case R.id.tv_random:
                mStrPasswd = RandomUtils.genRandomNum(8);
                mltAddpasswordBoxPassword.setText(mStrPasswd);
                break;
        }
    }

    /**
     * 更新密码箱
     */
    private void updatePassWdBox()
    {
        try
        {
            HttpParams params = new HttpParams();
            params.put("id", mStrUserId);
            params.put("token", mStrUserToken);
            params.put("name", mStrName);
            params.put("account", mStrAccount);
//            String key = RSAUtils.encryptBASE64(MD5Utils.getMD5String(mStrUserId)).trim();
//            String mPasswd = AESUtils.encrypt(mStrPasswd.getBytes(), key);
//            params.put("passWord", Utils.encryptBASE64(sm.getInstance().sm4CbcEncrypt(mStrPasswd.getBytes(), mStrPasswd.getBytes().length, sm.getInstance().sm3(mStrUserId.getBytes(),mStrUserId.getBytes().length))));
            params.put("passWord", mStrPasswd);
            params.put("url", mStrWebSite);
            params.put("passBoxId", mStrId);
            MyHttpsUtils.post(ConstantUitls.REQUEDT_URL + ConstantUitls.UPDATEPASSBOX, params, new MyHttpsUtils.ResultCallback()
            {
                @Override
                public void onSuccess(String response)
                {
                    ChangeListener listener = (ChangeListener) getActivity();
                    listener.onChangeListener(true);
                    ToastUtils.showToast(getActivity(), "更新数据成功");
                    mTvRight.setEnabled(true);
                    dismiss();
                }

                @Override
                public void onFailure(String failReason)
                {
                    ToastUtils.showToast(getActivity(), "更新数据失败");
                    mTvRight.setEnabled(true);
                }
            });
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    //添加密码箱
    private void addPassBox()
    {
        try
        {
            HttpParams params = new HttpParams();
            params.put("id", mStrUserId);
            params.put("token", mStrUserToken);
            params.put("name", mStrName);
            params.put("account", mStrAccount);

//            String key = RSAUtils.encryptBASE64(MD5Utils.getMD5String(mStrUserId)).trim();
//            String mPasswd = AESUtils.encrypt(mStrPasswd.getBytes(), key);
//            params.put("passWord", Utils.encryptBASE64(sm.getInstance().sm4CbcEncrypt(sm.getInstance().sm3(mStrUserId.getBytes(), mStrUserId.getBytes().length), 32, mStrPasswd.getBytes())).trim());
//            byte[] secPasswd = sm.getInstance().sm4CbcEncrypt(mStrPasswd.getBytes(), mStrPasswd.getBytes().length, sm.getInstance().sm3(mStrUserId.getBytes(), mStrUserId.getBytes().length));
//            params.put("passWord", Utils.encryptBASE64(secPasswd));
            params.put("passWord", mStrPasswd);
            params.put("url", mStrWebSite);
            MyHttpsUtils.post(ConstantUitls.REQUEDT_URL + ConstantUitls.ADDPASSBOX, params, new MyHttpsUtils.ResultCallback()
            {
                @Override
                public void onSuccess(String response)
                {
                    ChangeListener listener = (ChangeListener) getActivity();
                    listener.onChangeListener(true);
                    ToastUtils.showToast(getActivity(), "添加数据成功");
                    mTvRight.setEnabled(true);
                    dismiss();
                }

                @Override
                public void onFailure(String failReason)
                {
                    ToastUtils.showToast(getActivity(), "添加数据失败");
                    mTvRight.setEnabled(true);
                }
            });
        } catch (Exception e)
        {
            e.printStackTrace();
        }

    }

    /**
     * 判断字段是否为空
     *
     * @return
     */
    private boolean checkEmpty()
    {
        if (mStrName.length() <= 0)
        {
            ToastUtils.showToast(getActivity(), "名称不能为空");
            return false;
        }

        if (mStrAccount.length() <= 0)
        {
            ToastUtils.showToast(getActivity(), "账号不能为空");
            return false;
        }
        if (mStrPasswd.length() < 6)
        {
            ToastUtils.showToast(getActivity(), "密码不能小于6位");
            return false;
        }
        return true;
    }

    public interface ChangeListener
    {
        void onChangeListener(boolean change);
    }
}
